var models = require('../models');
var Reply = models.Reply;
var User = models.User;
var EventProxy = require('eventproxy');
var tools = require('../common/tools');
var _ = require('lodash');
var config = require('../config');

exports.queryList = function (query, options, callback) {
	var ep = new EventProxy();
	ep.fail(callback);

	Reply.find(query, null, options, ep.done(function (replies) {
		ep.after('author', replies.length, function () {
			_.compact(replies);
			callback(null, '', replies);
		});
		replies.forEach(function (reply, i) {
			reply.createAtFormatted = tools.formatDate(reply.createAt);
			User.findById(reply.authorId, ep.done(function (user) {
				if (!user)
					replies[i] = null;
				else
					reply.author = user;
				ep.emit('author');
			}));
		});
	}));
};

exports.queryPage = function (query, callback) {
	Reply.count(query,function(err,count){
		if(err)return callback(err);
		var pageTotal=Math.ceil(count/config.replyPageLimit)
		callback(null, pageTotal);
	});
};